#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/healthz/views_check_codename.py
# Compiled at: 2017-11-16 15:44:28
import os
from importlib import import_module
from django.http import HttpResponse
from common.base_utils import smart_upper
from components.esb_conf import _rel_path, CUSTOM_APIS_REL_PATH
from esb.utils import fpath_to_module
from esb.component.base import ComponentsManager

def check_custom_codename(request):
    """check custom component codename"""
    component_codename = request.GET.get('codename')
    component_manager = ComponentsManager()
    file_import_error = {}
    comp_config = {'path': _rel_path(CUSTOM_APIS_REL_PATH),
       'name_prefix': 'generic.'
       }
    for current_folder, folders, files in os.walk(comp_config['path']):
        for filename in files:
            filename = os.path.join(current_folder, filename)
            if filename.endswith('.py') and component_manager.should_register(filename):
                try:
                    module = import_module(fpath_to_module(filename))
                    component_manager.register_by_module(module, config=comp_config)
                except Exception as ex:
                    file_import_error[filename] = 'Exception: %s' % str(ex)

    error_msg = []
    if component_codename:
        try:
            prefix, sys_name, component_name = component_codename.split('.')
        except:
            return HttpResponse('codename "%s" does not math the rule generic.xxx.xxx, please check' % component_codename)

        if component_codename in component_manager.get_registed_components():
            return HttpResponse('component "%s" exists, if the visit prompts the error message "Not found, component class not found", please restart the esb service' % component_codename)
        error_msg.append('component "%s" does not exist, please check the following steps:' % component_codename)
        error_msg.append('1. component path is "%s", please check whether the component file exists' % comp_config['path'])
        error_msg.append('2. component class name should be "%s", please check' % smart_upper(component_name))
        error_msg.append('3. uppercase of compoennt attribute sys_name should be "%s", please check' % sys_name.upper())
    if file_import_error:
        error_msg.append('\n')
        error_msg.append('There are some components loaded exception, please repair:')
        error_msg.extend([ ('\n').join(item) for item in sorted(file_import_error.iteritems(), key=lambda x: x[0]) ])
    return HttpResponse(content=('\n').join(error_msg) or 'OK', content_type='text/plain')
